package com.example.housesrv.service;


import com.example.housesrv.common.BeanHelper;
import com.example.housesrv.common.HouseUserType;
import com.example.housesrv.mapper.HouseMapper;
import com.example.housesrv.model.House;
import com.example.housesrv.model.HouseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class HouseService {

    @Autowired
    private HouseMapper houseMapper;

    /**
     * 1. 添加房产
     * 2. 绑定房产到用户关系
     * @param house
     * @param userId
     */
    @Transactional(rollbackFor=Exception.class)
    public void addHouse(House house, Long userId) {
        BeanHelper.setDefaultProp(house, House.class);
        BeanHelper.onInsert(house);
        houseMapper.insert(house);
        bindUser2House(house.getId(),userId, HouseUserType.SALE);
    }

    @Transactional(rollbackFor = Exception.class)
    public void bindUser2House(Long id, Long userId, HouseUserType sale) {
        HouseUser existHouseUser  = houseMapper.selectHouseUser(userId, id, sale.value);
        if (existHouseUser != null) {
            return;
        }
        HouseUser houseUser = new HouseUser();
        houseUser.setHouseId(id);
        houseUser.setUserId(userId);
        houseUser.setType(sale.value);
        BeanHelper.setDefaultProp(houseUser, HouseUser.class);
        BeanHelper.onInsert(houseUser);
        houseMapper.insertHouseUser(houseUser);
    }

    /**
     * 注意这里逻辑做了修改:当售卖时只能将房产下架，不能解绑用户关系
     *                   当收藏时可以解除用户收藏房产这一关系
     * 解绑操作1.
     * @param houseId
     * @param userId
     * @param type
     */
    public void unbindUser2House(Long houseId, Long userId, HouseUserType type) {
        if(type.equals(HouseUserType.SALE)) {
            houseMapper.downHouse(houseId);
        } else {
            houseMapper.deleteHouseUser(houseId,userId,type.value);
        }
    }
}
